package com.zx.system.block.mapstruct;


import com.zx.core.context.TenantContextHolder;
import com.zx.core.enums.GenderEnum;
import com.zx.core.enums.StatusEnum;
import com.zx.feign.client.dto.GetSysUserResponseDTO;
import com.zx.system.block.model.SysUser;
import com.zx.system.block.param.UserParam;
import com.zx.system.block.vo.SysUserVO;
import org.mapstruct.AfterMapping;
import org.mapstruct.Mapper;
import org.mapstruct.MappingTarget;
import org.mapstruct.ReportingPolicy;
import org.mapstruct.factory.Mappers;

/**
 * <p>
 * description: 用户参数映射 <br>
 * create: 2024-10-29 21:46
 * </p>
 *
 * @author zhou  xun
 */
@Mapper(unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface UserMapStructMapper {
    UserMapStructMapper INSTANCE = Mappers.getMapper(UserMapStructMapper.class);

    /**
     * 将UserParam转换为SysUser实体
     *
     * @param userParam 用户参数
     * @return SysUser实体
     */
    SysUser userParamToSysUser(UserParam userParam);

    /**
     * 将SysUser实体转换为SysUserVO视图对象
     *
     * @param sysUser 用户实体
     * @return SysUserVO视图对象
     */
    SysUserVO sysUserToSysUserVO(SysUser sysUser);

    GetSysUserResponseDTO sysUserToSysUserDTO(SysUser sysUser);

    /**
     * 在映射完成后，设置描述性字段
     *
     * @param sysUser   用户实体
     * @param sysUserVO 用户VO
     */
    @AfterMapping
    default void setDescriptions(SysUser sysUser, @MappingTarget SysUserVO sysUserVO) {
        // 设置性别描述
        String sex = sysUser.getSex();
        if (sex != null && !sex.isEmpty()) {
            try {
                Integer sexValue = Integer.valueOf(sex);
                GenderEnum genderEnum = GenderEnum.getGenderBySexValue(sexValue);
                if (genderEnum != null) {
                    sysUserVO.setSexDesc(genderEnum.getGenderName());
                }
            } catch (NumberFormatException e) {
                // 忽略转换异常
            }
        }

        // 设置状态描述
        Integer status = sysUser.getStatus();
        StatusEnum statusEnum = StatusEnum.getEnumByCode(status);
        if (statusEnum != null) {
            sysUserVO.setStatusDesc(statusEnum.getDesc());
        }
    }

    /**
     * 在映射完成后，设置租户名
     *
     * @param sysUser   用户实体
     * @param sysUserVO 用户VO
     */
    @AfterMapping
    default void setTenantName(SysUser sysUser, @MappingTarget SysUserVO sysUserVO) {
        sysUserVO.setTenantName(TenantContextHolder.getTenantName());
    }
}